<template>
  <div>
    <!-- 客户列表 -->
    <el-card class="customer_card">
      <el-form
        :model="searchForm"
        ref="searchRef"
        inline
        class="customer_search"
        @keydown.enter="getList"
      >
        <el-form-item prop="customerName" label="姓名">
          <el-input
            v-model="searchForm.customerName"
            placeholder="请输入姓名"
            class="form_input"
          />
        </el-form-item>

        <el-form-item prop="customerTel" label="联系方式">
          <el-input
            v-model="searchForm.customerTel"
            placeholder="请输入联系方式"
            class="form_input"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            icon="Search"
            @click="handleSearch"
            class="btn"
            >查询</el-button
          >
          <el-button icon="Refresh" @click="handleReset" class="btn"
            >重置</el-button
          >
          <el-button v-if="is_type == 'tile'" @click="handleChangeList('fold')">
            <el-icon> <Files /> </el-icon>折叠列表
          </el-button>
          <el-button v-else @click="handleChangeList('tile')">
            <el-icon> <List /> </el-icon>平铺列表
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="height: calc(100vh - 10rem)" class="customer_card mt-1">
      <div class="flex justify-end mb-[0.2rem]">
        <el-button
          type="primary"
          icon="Plus"
          class="btn"
          @click="openDrawer(0)"
        >
          新增
        </el-button>
      </div>

      <el-table
        :data="tableData"
        style="height: calc(100vh - 15rem)"
        v-if="is_type == 'fold'"
      >
        <el-table-column type="expand" fixed="left">
          <template #default="{ row }">
            <el-table :data="row.customers" border class="w-[95%] mx-auto">
              <el-table-column
                label="检查卡姓名"
                prop="name"
                show-overflow-tooltip
                fixed
              />
              <el-table-column
                label="联系方式"
                prop="phone"
                show-overflow-tooltip
              />
              <el-table-column label="性别">
                <template #default="props">
                  {{
                    props.row.sex == 1 ? "男" : props.row.sex == 2 ? "女" : ""
                  }}
                </template>
              </el-table-column>
              <el-table-column label="检查卡关系">
                <template #default="props">
                  <el-tag type="primary">
                    {{ props.row.baseRelationName }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="检查档案" prop="caseNum" />
              <el-table-column
                label="职业"
                prop="occupationName"
                show-overflow-tooltip
              />
              <el-table-column
                label="用镜距离"
                prop="eyeUsageDistanceName"
                show-overflow-tooltip
              />
              <el-table-column
                label="工作环境"
                prop="workEnvName"
                show-overflow-tooltip
              />
              <el-table-column label="操作" min-width="150" align="center">
                <template #default="props">
                  <el-button
                    type="primary"
                    link
                    @click="handleDetailBtn(props.row)"
                  >
                    <el-icon> <InfoFilled /> </el-icon>详情
                  </el-button>

                  <el-button
                    type="primary"
                    link
                    @click="handleCheckBtn(props.row, row)"
                  >
                    <el-icon> <Document /> </el-icon>检查
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column
          label="姓名"
          prop="customerName"
          fixed
          show-overflow-tooltip
        />
        <el-table-column
          label="联系方式"
          prop="customerTel"
          show-overflow-tooltip
        />
        <el-table-column label="性别" prop="name">
          <template #default="{ row }">
            <span v-if="row.sex === 1">男</span>
            <span v-else-if="row.sex === 2">女</span>
            <span v-else>---</span>
          </template>
        </el-table-column>
        <el-table-column label="年龄" prop="age" />
        <el-table-column
          label="客户来源"
          prop="customerSource"
          show-overflow-tooltip
        />
        <el-table-column
          label="账号来源"
          prop="accountSource"
          show-overflow-tooltip
        />
        <el-table-column
          label="训练次数(双击数字编辑)"
          align="center"
          width="180"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <div
              class="w-full cursor-pointer"
              @dblclick="handleDbclickTrainCount(row)"
            >
              <el-tag type="primary">
                {{ row.trainingCount || 0 }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="remark"
          label="备注"
          align="center"
          show-overflow-tooltip
        />

        <el-table-column
          label="操作"
          align="center"
          :min-width="200"
          fixed="right"
        >
          <template #default="{ row }">
            <el-button type="primary" link @click="openDrawer(row.id)">
              <el-icon>
                <Edit />
              </el-icon>
              编辑
            </el-button>
            <el-button type="primary" link @click="handleCheckCardBtn(row)">
              <el-icon>
                <Plus />
              </el-icon>
              检查卡
            </el-button>
            <el-button type="primary" link @click="handleReturnVisit(row)">
              <el-icon> <PhoneFilled /> </el-icon>回访
            </el-button>
            <el-button type="danger" link @click="handleRemove(row.id)">
              <el-icon>
                <Delete />
              </el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>

        <template #empty> 暂无客户 </template>
      </el-table>

      <el-table :data="tableData" style="height: calc(100vh - 15rem)" v-else>
        <el-table-column prop="name" label="受检人名称" align="center" />
        <el-table-column prop="phone" label="受检人联系方式" align="center" />
        <!-- <el-table-column prop="customerName" label="客户姓名" align="center" /> -->
        <!-- <el-table-column
          prop="baseRelationName"
          label="亲属关系"
          align="center"
        >
          <template #default="{ row }">
            <el-tag type="primary">
              {{ row.baseRelationName || "" }}
            </el-tag>
          </template>
        </el-table-column> -->
        <el-table-column
          prop="occupationName"
          label="职业"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          prop="workEnvName"
          label="工作环境"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          prop="eyeUsageDistanceName"
          label="用眼距离"
          align="center"
        />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleDetailBtn(row)">
              <el-icon> <InfoFilled /> </el-icon>详情
            </el-button>

            <el-button type="primary" link @click="handleCheckBtn(row)">
              <el-icon> <Document /> </el-icon>检查
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <PagingQuery
        :page="page"
        :pageSize="pageSize"
        :total="total"
        @getList="getList"
        class="mt-[0.5rem]"
      />
    </el-card>

    <!-- 1.新增或者修改客户信息 -->
    <el-drawer
      v-model="drawer"
      destroy-on-close
      size="40%"
      :title="detailId == 0 ? '新增客户/受检人' : '编辑客户/受检人'"
    >
      <InsertUpdate
        :detailId="detailId"
        :workEnvList="workEnvList"
        :occupationList="occupationList"
        :eyeDistanceList="eyeDistanceList"
        ref="insertUpdateRef"
        @handleSuccessBack="handleSuccessCreateCustomer"
        @handleBack="handleErrorCreateCustomer"
      />

      <template #footer>
        <el-button @click="handleCancel">取 消</el-button>
        <el-button
          type="primary"
          @click="handleInsertCustomer"
          :loading="customer_loading"
        >
          {{ customer_loading ? "提 交 中" : "提 交" }}
        </el-button>
      </template>
    </el-drawer>

    <!-- 2.添加检查卡 -->
    <el-drawer
      v-model="create_check_drawer"
      title="添加检查卡"
      size="80%"
      destroy-on-close
    >
      <CreateCheck
        ref="createCheckRef"
        :checkForm="checkForm"
        :baseList="baseList"
        :workEnvList="workEnvList"
        :occupationList="occupationList"
        :eyeDistanceList="eyeDistanceList"
        @handleBack="handleSuccessCheck"
      />
      <template #footer>
        <el-button @click="handleCancel">取 消</el-button>
        <el-button
          type="primary"
          @click="handleSubmitCheck"
          :loading="check_card_loading"
        >
          {{ check_card_loading ? "提 交 中" : "提 交" }}
        </el-button>
      </template>
    </el-drawer>

    <!-- 3.详情 -->
    <el-drawer v-model="detail_drawer" destroy-on-close size="90%" title="详情">
      <DetailPage :detailForm="detailForm" />
    </el-drawer>

    <!-- 4.回访 -->
    <el-drawer
      v-model="visit_drawer"
      destroy-on-close
      size="40%"
      title="回访记录"
    >
      <ReturnVisit :detailForm="visitForm" @handleBack="handleVisitBack" />
    </el-drawer>

    <!-- 6.添加检查 -->
    <el-drawer
      v-model="insert_check_drawer"
      destroy-on-close
      size="40%"
      title="添加检查"
    >
      <InsertCheck
        ref="insert_check_ref"
        :detailForm="insert_check_form"
        @handleBack="handleInsertCheckSuccessBack"
      />

      <template #footer>
        <el-button @click="insert_check_drawer = false">取消</el-button>
        <el-button
          type="primary"
          :loading="insert_check_loading"
          @click="handleSubmitInsertCheck"
        >
          {{ insert_check_loading ? "提交中..." : "提 交" }}
        </el-button>
      </template>
    </el-drawer>

    <!-- 7.修改训练次数 -->
    <el-drawer
      v-model="train_drawer"
      destroy-on-close
      size="35%"
      title="修改训练次数"
    >
      <UpdateTrain :detailForm="trainForm" @handleBack="handleSuccessTrain" />
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { cloneDeep } from "lodash";
import PagingQuery from "@/components/PagingQuery.vue";
import InsertUpdate from "./component/InsertUpdate.vue";
import CreateCheck from "./component/CreateCheck.vue";
import InsertCheck from "./component/InsertCheck.vue";
import DetailPage from "./component/DetailPage.vue";
import UpdateTrain from "./component/UpdateTrain.vue";
import ReturnVisit from "./component/ReturnVisit.vue";
import { handleApiResponse } from "@/utils/request.js";
import {
  GetTreeCustomerList,
  ListCustomerOccupation,
  ListCustomerEyeUsageDistance,
  ListCustomerWorkEnv,
  DeleteCustomerById,
  GetRelativeBaseList,
  GetRelativesByQuery,
} from "../../../../wailsjs/go/api/CustomerApi.js";
import { UpdateCustomerTrainCount } from "../../../../wailsjs/go/api/OrderApi";

onMounted(() => {
  getList();
  getOccupationList();
  getWorkEnvList();
  getEyeUsageDistanceList();
  getBaseList();
});

const searchRef = ref(null);
const searchForm = ref({
  customerName: "",
  customerTel: "",
});

const handleSearch = () => {
  getList();
};
const handleReset = () => {
  searchRef.value.resetFields();
  getList();
};

const page = ref(1);
const pageSize = ref(10);
const total = ref(0);
const tableData = ref([]);

const is_type = ref("fold"); // 1.折叠fold 2.平铺tile
const handleChangeList = (e) => {
  is_type.value = e;

  getList();
};
const getList = (e) => {
  tableData.value = [];
  if (is_type.value == "fold") {
    getTreeList(e);
  } else {
    getTileList(e);
  }
};
// 折叠列表
const getTreeList = (e) => {
  if (e) {
    page.value = e.page;
    pageSize.value = e.pageSize;
  }
  handleApiResponse(() =>
    GetTreeCustomerList({
      page: page.value,
      pageSize: pageSize.value,
      ...searchForm.value,
    })
  ).then((res) => {
    if (res.code == 0) {
      // console.log(res);
      tableData.value = res.data.customers || [];
      total.value = res.data.total || 0;
    }
  });
};
// 平铺列表
const getTileList = (e) => {
  if (e) {
    page.value = e.page;
    pageSize.value = e.pageSize;
  }
  handleApiResponse(() =>
    GetRelativesByQuery({
      page: page.value,
      pageSize: pageSize.value,
      ...searchForm.value,
    })
  ).then((res) => {
    if (res.code == 0) {
      // console.log(res);
      tableData.value = res.data.list || [];
    }
  });
};

// 1.新增或者修改客户信息
const drawer = ref(false);
const insertUpdateRef = ref(null);
const detailId = ref(null); // 0 新增 !0 编辑
const openDrawer = (id) => {
  detailId.value = id;
  drawer.value = true;
};

const handleCancel = () => {
  drawer.value = false;
};

const customer_loading = ref(false);
const handleInsertCustomer = () => {
  customer_loading.value = true;
  insertUpdateRef.value.handleSubmitCustomer();
};

const handleSuccessCreateCustomer = () => {
  customer_loading.value = false;
  getList();
  drawer.value = false;
};
const handleErrorCreateCustomer = () => {
  customer_loading.value = false;
};

// 2.添加检查卡
const create_check_drawer = ref(false);
const createCheckRef = ref(null);
const check_card_loading = ref(false);
const checkForm = ref({});
const handleCheckCardBtn = (row) => {
  checkForm.value = row;
  create_check_drawer.value = true;
};

const handleSubmitCheck = async () => {
  createCheckRef.value?.handleSubmit();
};
const handleSuccessCheck = (val) => {
  if (val == 1) {
    check_card_loading.value = true;
    return;
  }
  check_card_loading.value = false;
  create_check_drawer.value = false;
  getList();
};

// 3.删除
const handleRemove = (id) => {
  ElMessageBox.confirm("是否删除该客户?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    handleApiResponse(() => DeleteCustomerById({ customerId: id })).then(
      (res) => {
        if (res.code == 0) {
          ElMessage.success("删除成功");
          getList();
        }
      }
    );
  });
};

// 4.回访
const visit_drawer = ref(false);
const visitForm = ref({});
const handleReturnVisit = (row) => {
  visitForm.value = cloneDeep(row);
  visit_drawer.value = true;
};
const handleVisitBack = (val) => {
  visit_drawer.value = false;
};

// 5.详情
const detail_drawer = ref(false);
const detailForm = ref({});
const handleDetailBtn = (row) => {
  detailForm.value = row;
  detail_drawer.value = true;
};

// 6.添加检查
const insert_check_drawer = ref(false);
const insert_check_ref = ref(null);
const insert_check_loading = ref(false);
const insert_check_form = ref({});
const handleCheckBtn = (child, item) => {
  let form = cloneDeep(child);

  insert_check_form.value = {
    customerId: form.customerId,
    customerName: is_type.value == "tile" ? form.name : item.customerName,
    customerPhone: is_type.value == "tile" ? form.phone : item.customerTel,
    relationId: form.relationId,
    relationName: form.name,
    baseRelationId: form.baseRelationId,
    baseRelationName: form.baseRelationName,
    age: form.age,
    sex: form.sex,
    phone: form.phone,
    occupation: form.occupationName,
    eyeDistance: form.eyeUsageDistanceName,
    workEnvironment: form.workEnvName,
    projectList: form.projectList || [],
    projectId: form.projectId || [],
  };
  insert_check_drawer.value = true;
};
const handleSubmitInsertCheck = () => {
  insert_check_ref.value?.handleSubmit();
};
const handleInsertCheckSuccessBack = (val) => {
  if (val == 1) {
    insert_check_loading.value = true;
    return;
  }
  insert_check_loading.value = false;
  insert_check_drawer.value = false;
  getList();
};

// 7.修改训练次数
const train_drawer = ref(false);
const trainForm = ref({});
const handleDbclickTrainCount = (row) => {
  row.trainCount = row.trainingCount;
  trainForm.value = cloneDeep(row);
  train_drawer.value = true;
};
const handleSuccessTrain = (val) => {
  if (val == 1) {
    getList();
  }
  train_drawer.value = false;
};

const baseList = ref([]); // 亲属列表
async function getBaseList() {
  handleApiResponse(() => GetRelativeBaseList()).then((res) => {
    if (res.code == 0) {
      baseList.value = res.data.list || [];
    }
  });
}

const workEnvList = ref([]); // 工作环境列表
const occupationList = ref([]); // 职业列表
const eyeDistanceList = ref([]); // 用眼距离列表
async function getOccupationList() {
  handleApiResponse(() => ListCustomerOccupation()).then((res) => {
    if (res.code == 0) {
      occupationList.value = res.data.list || [];
    }
  });
}
async function getWorkEnvList() {
  handleApiResponse(() => ListCustomerWorkEnv()).then((res) => {
    if (res.code == 0) {
      workEnvList.value = res.data.list || [];
    }
  });
}
async function getEyeUsageDistanceList() {
  handleApiResponse(() => ListCustomerEyeUsageDistance()).then((res) => {
    if (res.code == 0) {
      eyeDistanceList.value = res.data.list || [];
    }
  });
}
</script>

<style scoped lang="scss">
.customer_card :deep(.el-card__body) {
  @apply px-[0.5rem] py-[0.5rem];
}
.customer_search :deep(.el-form-item) {
  margin-bottom: 0;
}
.form_input {
  @apply w-[7rem];
}

.btn {
  @apply w-[4.5rem];
}
</style>